package com.example.onlinetaxi.ui.activity.MainPage;

import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.callback.OrderCallBack.GetOrderCallBack;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.dto.OrderDto.CompletedOrderDto;
import com.example.onlinetaxi.dto.OrderDto.OrderDTO;
import com.example.onlinetaxi.dto.OrderDto.ReceivedOrderDto;
import com.example.onlinetaxi.ui.activity.MainPage.OrderFragments.CancelOrderFragment;
import com.example.onlinetaxi.ui.activity.MainPage.OrderFragments.CompleteOrderFragment;
import com.example.onlinetaxi.ui.activity.MainPage.OrderFragments.DoingOrderFragment;
import com.example.onlinetaxi.ui.activity.MainPage.OrderFragments.WaitingOrderFragment;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.TimeUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

// 预定界面
public class OrderFragment extends Fragment implements View.OnClickListener {

    private View rootView;
    // fragments
    private CancelOrderFragment cancelOrderFragment = new CancelOrderFragment();
    private WaitingOrderFragment waitingOrderFragment = new WaitingOrderFragment();
    private DoingOrderFragment doingOrderFragment = new DoingOrderFragment();
    private CompleteOrderFragment completeOrderFragment = new CompleteOrderFragment();
    // 订单导航栏控件中的布局、图片和按钮
    // 取消的订单
    private LinearLayout cancelOrderLayout;
    private ImageView cancelOrderImg;
    private TextView cancelOrderTv;
    // 等待接单的订单
    private LinearLayout waitingOrderLayout;
    private ImageView waitingOrderImg;
    private TextView waitingOrderTv;
    // 正在执行的订单
    private LinearLayout doingOrderLayout;
    private ImageView doingOrderImg;
    private TextView doingOrderTv;
    // 完成的订单
    private LinearLayout completeOrderLayout;
    private ImageView completeOrderImg;
    private TextView completeOrderTv;
    // 请求参数
    private Map<String, String> map = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order, container, false);

        initView();

        initEvent();

        // 关闭加载框
        MainActivity.closeProgressDialog();

        return rootView;
    }

    private void initEvent() {
        // 初始化按钮
        cancelOrderLayout.setOnClickListener(this);
        waitingOrderLayout.setOnClickListener(this);
        doingOrderLayout.setOnClickListener(this);
        completeOrderLayout.setOnClickListener(this);

        // 获取订单数据
        initOrderList();

        waitingOrderFragment.setGetOrderCallBack(new GetOrderCallBack() {
            @Override
            public void refreshOrder() {
                // 重新获取订单信息
                initOrderList();
            }
        });
        cancelOrderFragment.setGetOrderCallBack(new GetOrderCallBack() {
            @Override
            public void refreshOrder() {
                // 重新获取订单信息
                initOrderList();
            }
        });
        completeOrderFragment.setGetOrderCallBack(new GetOrderCallBack() {
            @Override
            public void refreshOrder() {
                // 重新获取订单信息
                initOrderList();
            }
        });
        doingOrderFragment.setGetOrderCallBack(new GetOrderCallBack() {
            @Override
            public void refreshOrder() {
                // 重新获取订单信息
                initOrderList();
            }
        });
    }


    private void initOrderList() {
        // 从后端数据库获取所有订单信息
        map.put("phone", LocalStorage.phone);

        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "order", "getOrderList");
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);

        if (dataResponse.getCode().equals("200")) {
            // 创建订单列表
            List<OrderDTO> waitingOrderList = new ArrayList<>();
            List<CompletedOrderDto> cancelOrderList = new ArrayList<>();
            List<ReceivedOrderDto> doingOrderList = new ArrayList<>();
            List<CompletedOrderDto> completeOrderList = new ArrayList<>();

            Map<String, String> responseMap = dataResponse.getData();
            Set<String> keys = responseMap.keySet();

            for (String key : keys) {
                // 将json字符串转换回orderDTO
                Gson gson = new Gson();
                CompletedOrderDto order = null;
                try {
                    // 将order的两个时间切换为指定格式
                    order = TimeUtil.setRightTimeFormat(gson.fromJson(responseMap.get(key), CompletedOrderDto.class));
                } catch (Exception e) {

                }

                if (order!=null){
                    // 将order分配到不同的列表
                    if (order.getState().equals("0")) {
                        // 等待接单
                        waitingOrderList.add(order);
                    } else if (order.getState().equals("1") || order.getState().equals("5") || order.getCancelState().equals("2")) {
                        // 已取消或撤销成功的订单
                        cancelOrderList.add(order);
                    } else if ((order.getState().equals("3") || order.getState().equals("4")) && !order.getCancelState().equals("2")) {
                        // 正在进行
                        doingOrderList.add(order);
                    } else if (order.getState().equals("7") || order.getState().equals("8")) {
                        completeOrderList.add(order);
                    }
                }
            }
            // 将列表分发到每一个fragment
            waitingOrderFragment.setOrderList(waitingOrderList);
            cancelOrderFragment.setOrderList(cancelOrderList);
            doingOrderFragment.setOrderList(doingOrderList);
            completeOrderFragment.setOrderList(completeOrderList);
        }
    }

    private void initView() {
        // 进行初始化
        cancelOrderLayout = rootView.findViewById(R.id.cancel_order_layout);
        cancelOrderImg = rootView.findViewById(R.id.cancel_order_img);
        cancelOrderTv = rootView.findViewById(R.id.cancel_order_tv);

        waitingOrderLayout = rootView.findViewById(R.id.waiting_order_layout);
        waitingOrderImg = rootView.findViewById(R.id.waiting_order_img);
        waitingOrderTv = rootView.findViewById(R.id.waiting_order_tv);

        doingOrderLayout = rootView.findViewById(R.id.doing_order_layout);
        doingOrderImg = rootView.findViewById(R.id.doing_order_img);
        doingOrderTv = rootView.findViewById(R.id.doing_order_tv);

        completeOrderLayout = rootView.findViewById(R.id.complete_order_layout);
        completeOrderImg = rootView.findViewById(R.id.complete_order_img);
        completeOrderTv = rootView.findViewById(R.id.complete_order_tv);

        // 设置刚开始的颜色
        waitingOrderTv.setTextColor(getResources().getColor(R.color.perfect_orange));
        waitingOrderImg.setColorFilter(getResources().getColor(R.color.perfect_orange));
        cancelOrderTv.setTextColor(Color.GRAY);
        cancelOrderImg.setColorFilter(Color.GRAY);
        doingOrderTv.setTextColor(Color.GRAY);
        doingOrderImg.setColorFilter(Color.GRAY);
        completeOrderTv.setTextColor(Color.GRAY);
        completeOrderImg.setColorFilter(Color.GRAY);

        // 设置刚开始的fragment
        replaceFragment(waitingOrderFragment);
    }


    // 进行碎片之间的切换
    private void replaceFragment(Fragment fragment) {
        // 获取碎片管理类
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        // 开启碎片事物
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // 创建事务
        fragmentTransaction.replace(R.id.order_fragment, fragment);
        // 提交事务
        fragmentTransaction.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel_order_layout:
                // 进行按钮样式的修改
                cancelOrderTv.setTextColor(getResources().getColor(R.color.perfect_orange));
                cancelOrderImg.setColorFilter(getResources().getColor(R.color.perfect_orange));
                waitingOrderTv.setTextColor(Color.GRAY);
                waitingOrderImg.setColorFilter(Color.GRAY);
                doingOrderTv.setTextColor(Color.GRAY);
                doingOrderImg.setColorFilter(Color.GRAY);
                completeOrderTv.setTextColor(Color.GRAY);
                completeOrderImg.setColorFilter(Color.GRAY);
                replaceFragment(cancelOrderFragment);
                break;
            case R.id.waiting_order_layout:
                // 进行按钮样式的修改
                waitingOrderTv.setTextColor(getResources().getColor(R.color.perfect_orange));
                waitingOrderImg.setColorFilter(getResources().getColor(R.color.perfect_orange));
                cancelOrderTv.setTextColor(Color.GRAY);
                cancelOrderImg.setColorFilter(Color.GRAY);
                doingOrderTv.setTextColor(Color.GRAY);
                doingOrderImg.setColorFilter(Color.GRAY);
                completeOrderTv.setTextColor(Color.GRAY);
                completeOrderImg.setColorFilter(Color.GRAY);
                replaceFragment(waitingOrderFragment);
                break;
            case R.id.doing_order_layout:
                // 进行按钮样式的修改
                doingOrderTv.setTextColor(getResources().getColor(R.color.perfect_orange));
                doingOrderImg.setColorFilter(getResources().getColor(R.color.perfect_orange));
                waitingOrderTv.setTextColor(Color.GRAY);
                waitingOrderImg.setColorFilter(Color.GRAY);
                cancelOrderTv.setTextColor(Color.GRAY);
                cancelOrderImg.setColorFilter(Color.GRAY);
                completeOrderTv.setTextColor(Color.GRAY);
                completeOrderImg.setColorFilter(Color.GRAY);
                replaceFragment(doingOrderFragment);
                break;
            case R.id.complete_order_layout:
                // 进行按钮样式的修改
                completeOrderTv.setTextColor(getResources().getColor(R.color.perfect_orange));
                completeOrderImg.setColorFilter(getResources().getColor(R.color.perfect_orange));
                waitingOrderTv.setTextColor(Color.GRAY);
                waitingOrderImg.setColorFilter(Color.GRAY);
                doingOrderTv.setTextColor(Color.GRAY);
                doingOrderImg.setColorFilter(Color.GRAY);
                cancelOrderTv.setTextColor(Color.GRAY);
                cancelOrderImg.setColorFilter(Color.GRAY);
                replaceFragment(completeOrderFragment);
                break;
        }
    }

    // 解决界面二次打开，内嵌fragment空白问题
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (waitingOrderFragment != null) {
            FragmentManager f = getFragmentManager();
            if (f != null) {
                final FragmentTransaction ft = f.beginTransaction();
                if (ft != null) {
                    ft.remove(waitingOrderFragment).commitAllowingStateLoss();
                }
            }
        }
    }
}